<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="formData.id?'编辑部门':'新增部门'" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @blur="chackManager">
          <el-option
            v-for="user in employees"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <template #footer>
      <el-row type="flex" justify="center">
        <!-- 列被分为24 -->
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnOK">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentsDetail } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employee'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkNameRepeat = (rule, val, callback) => {
      // 判断有没有重名
      // 筛选出同一个父部门的子部门
      // 是否同名也要区别编辑和新增
      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = this.depts
        // 编辑时,以pid作为父部门的筛选条件
          .filter(item => item.pid === this.nodeData.pid)
        // 跟code一样 不能跟自己的id一样,不然就是自己,不算重名的  code和id相同是自己 code相同id不同是重复
          .some(item => item.name === val && item.id !== this.nodeData.id)
      } else {
        // 新增
        isRepeat = this.depts
          .filter(item => item.pid === this.nodeData.id)
          .some(item => item.name === val)
      }
      // 根据结果后续处理
      if (isRepeat) {
        // 失败
        callback(new Error('同一个部门不能同名'))
      } else {
        // 成功
        callback()
      }
    }
    const chackCodeRepeat = (rule, val, callback) => {
      // 是否有重复code
      // 根据新增编辑的情况区别校验
      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = this.depts.some(item => item.code === val && item.id !== this.nodeData.id)
      } else {
        // 新增
        isRepeat = this.depts.some(item => item.code === val)
      }
      // 后续处理报错
      isRepeat ? callback(new Error('部门编码必须唯一')) : callback()
    }
    return {
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 50, message: '长度不能大于50', trigger: 'blur' },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        code: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 50, message: '长度不能大于50', trigger: 'blur' },
          { trigger: 'blur', validator: chackCodeRepeat }
        ],
        manager: [
          { required: true, message: '该项不能为空', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 300, message: '长度不能大于300', trigger: 'blur' }
        ]
      },
      depts: [],
      employees: []
    }
  },
  async created() {
    // 立刻就获取数据
    this.getDepartments()
    // 进来获取员工列表
    this.employees = await getEmployeeSimple()
    // console.log(this.employees)
  },
  methods: {
    async getDepartments() {
      const { depts } = await getDepartments()
      // console.log(depts)
      this.depts = depts
    },
    chackManager() {
      // 增加一个延时器 有选中的数据就不会报该项不能为空错误
      setTimeout(() => {
        // element ui 没有自动校验
      // 手动校验,element ui 提供了一个校验函数
        this.$refs.addDept.validateField('manager')
      }, 200)
    },
    async btnOK() {
      // 验证
      await this.$refs.addDept.validate()
      // 发请求
      await addDepartments({
        ...this.formData,
        pid: this.nodeData.id
      })
      // 提醒用户
      this.$message.success('操作成功')
      // 关闭弹窗
      // 父传子方式修改 prop
      this.$emit('update:showDialog', false)
      // 更新获取数据
      this.getDepartments()
      // 更新页面
      this.$emit('addDepartments')
    },
    btnCancel() {
      // 避免清空不完整,直接将整个表单恢复原样
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // 重置为初始值
      // 清空校验
      this.$refs.addDept.resetFields()
      // 点关闭按钮关闭
      this.$emit('update:showDialog', false)
    },
    async getDepartmentsDetail(id) {
      this.formData = await getDepartmentsDetail(id)
    }
  }
}
</script>

<style>

</style>
